﻿using Mapster;
using Microsoft.AspNetCore.Components;
using Microsoft.Extensions.DependencyInjection;
using MyCommon.Helper;
using MyModels.Logs;
using MySerilog.Extensions;
using Serilog.Events;
using Serilog.Sinks.PeriodicBatching;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MySerilog.Sink
{
    public class LogBatchingSink : IBatchedLogEventSink
    {
        //public LogBatchingSink(ISqlSugarClient  sqlSugar)
        //{
        //    _sqlSugar = sqlSugar;
        //}

        public ISqlSugarClient _sqlSugar { get; set; }
        public async Task EmitBatchAsync(IEnumerable<LogEvent> batch)
        {
            await WriteSqlLog(_sqlSugar, batch.FilterSqlLog());
        }

        public Task OnEmptyBatchAsync()
        {
            return Task.CompletedTask;
        }

        private async Task WriteSqlLog(ISqlSugarClient db, IEnumerable<LogEvent> batch)
        {
            if (!batch.Any()) return;
            var logs = new List<AuditSqlLog>();
            foreach (var logEvent in batch) {
                var log = logEvent.Adapt<AuditSqlLog>();
                log.Message = logEvent.RenderMessage();
                log.Properties = logEvent.Properties.ToJson();
                log.DateTime = logEvent.Timestamp.DateTime;
                logs.Add(log);
            }

            await db.AsTenant().InsertableWithAttr(logs).SplitTable().ExecuteReturnSnowflakeIdAsync();
        }
    }
}
